<template>
  <div class="coupon-container">
    <a-card>
      <!-- 搜索区域 -->
      <div class="search-wrapper">
        <a-form layout="inline" :model="searchForm">
          <div class="search-row">
            <a-form-item label="优惠券名称">
              <a-input v-model:value="searchForm.name" placeholder="请输入优惠券名称" />
            </a-form-item>
            <a-form-item label="优惠券类型">
              <a-select
                v-model:value="searchForm.type"
                placeholder="请选择类型"
                style="width: 160px"
                allowClear
              >
                <a-select-option :value="COUPON_TYPE.FIXED">{{ COUPON_TYPE_TEXT[COUPON_TYPE.FIXED] }}</a-select-option>
                <a-select-option :value="COUPON_TYPE.PERCENT">{{ COUPON_TYPE_TEXT[COUPON_TYPE.PERCENT] }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="是否秒杀">
              <a-select
                v-model:value="searchForm.isSeckill"
                placeholder="是否秒杀券"
                style="width: 160px"
                allowClear
              >
                <a-select-option :value="1">是</a-select-option>
                <a-select-option :value="0">否</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="search-buttons">
              <a-space>
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button @click="handleReset">重置</a-button>
              </a-space>
            </a-form-item>
            <!-- 操作按钮 -->
            <div >
              <a-button type="primary" @click="handleAdd">新增优惠券</a-button>
            </div>
          </div>
        </a-form>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="couponList"
        :loading="loading"
        :pagination="{
          ...pagination,
          showTotal: (total: number) => `总计 ${total} 条数据`
        }"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="record.type === COUPON_TYPE.PERCENT ? 'blue' : 'green'">
              {{ COUPON_TYPE_TEXT[record.type] || '未知类型' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'discountAmount'">
            <span v-if="record.type === COUPON_TYPE.PERCENT">{{ record.discountAmount }}%</span>
            <span v-else>¥{{ record.discountAmount }}</span>
          </template>
          <template v-if="column.key === 'validPeriod'">
            {{ formatDate(record.startTime) }} 至 {{ formatDate(record.endTime) }}
          </template>
          <template v-if="column.key === 'stock'">
            <a-tag :color="record.stock > 10 ? 'success' : 'warning'">
              {{ record.stock }}
            </a-tag>
          </template>
          <template v-if="column.key === 'isSeckill'">
            <a-tag :color="record.seckillStartTime ? 'volcano' : ''">
              {{ record.seckillStartTime ? '是' : '否' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'seckillPeriod'">
            <span v-if="record.seckillStartTime">
              {{ formatDateTime(record.seckillStartTime) }} 至 {{ formatDateTime(record.seckillEndTime) }}
            </span>
            <span v-else>-</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除这个优惠券吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑优惠券弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="600px"
      @ok="handleModalOk"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="优惠券名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入优惠券名称" />
        </a-form-item>
        
        <a-form-item label="优惠券类型" name="type">
          <a-select v-model:value="formState.type" placeholder="请选择优惠券类型">
            <a-select-option :value="COUPON_TYPE.FIXED">{{ COUPON_TYPE_TEXT[COUPON_TYPE.FIXED] }}</a-select-option>
            <a-select-option :value="COUPON_TYPE.PERCENT">{{ COUPON_TYPE_TEXT[COUPON_TYPE.PERCENT] }}</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="优惠金额/折扣" name="discountAmount">
          <a-input-number 
            v-model:value="formState.discountAmount" 
            :min="formState.type === COUPON_TYPE.PERCENT ? 1 : 0" 
            :max="formState.type === COUPON_TYPE.PERCENT ? 100 : 1000"
            :precision="formState.type === COUPON_TYPE.PERCENT ? 0 : 2"
            style="width: 100%"
            :addon-after="formState.type === COUPON_TYPE.PERCENT ? '%' : '元'"
          />
        </a-form-item>
        
        <a-form-item label="最低消费金额" name="minAmount">
          <a-input-number v-model:value="formState.minAmount" :min="0" :precision="2" style="width: 100%" addon-after="元" />
        </a-form-item>
        
        <a-form-item label="库存数量" name="stock">
          <a-input-number v-model:value="formState.stock" :min="1" style="width: 100%" />
        </a-form-item>
        
        <a-form-item label="有效时间" name="validTimeRange">
          <a-range-picker 
            v-model:value="timeRange" 
            show-time 
            format="YYYY-MM-DD HH:mm:ss" 
            style="width: 100%" 
          />
        </a-form-item>

        <a-form-item label="是否为秒杀券" name="isSeckill">
          <a-switch v-model:checked="formState.isSeckill" />
        </a-form-item>

        <template v-if="formState.isSeckill">
          <a-form-item label="秒杀开始时间" name="seckillStartTime">
            <a-date-picker 
              v-model:value="seckillStartTime" 
              show-time 
              format="YYYY-MM-DD HH:mm:ss" 
              style="width: 100%" 
              placeholder="请选择秒杀开始时间" 
            />
          </a-form-item>
          
          <a-form-item label="秒杀持续时间" name="seckillDuration">
            <a-row :gutter="8">
              <a-col :span="12">
                <a-input-number 
                  v-model:value="seckillDurationHours" 
                  :min="0" 
                  :max="72" 
                  style="width: 100%" 
                  addon-after="小时" 
                  @change="calculateSeckillEndTime"
                />
              </a-col>
              <a-col :span="12">
                <a-input-number 
                  v-model:value="seckillDurationMinutes" 
                  :min="0" 
                  :max="59" 
                  style="width: 100%" 
                  addon-after="分钟" 
                  @change="calculateSeckillEndTime"
                />
              </a-col>
            </a-row>
          </a-form-item>
          
          <a-form-item label="秒杀结束时间">
            <a-input disabled :value="formatDateTime(formState.seckillEndTime)" style="width: 100%" />
          </a-form-item>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { 
  addCouponUsingPost, 
  listCouponVoByPageUsingPost,
  updateCouponUsingPost,
  deleteCouponUsingPost
} from '@/api/couponController'
import type { Rule } from 'ant-design-vue/es/form'
import { COUPON_TYPE, COUPON_TYPE_TEXT, USER_COUPON_STATUS, USER_COUPON_STATUS_TEXT } from '@/constants/coupon'

// 搜索表单
const searchForm = ref({
  name: undefined,
  type: undefined,
  isSeckill: undefined,
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend'
})

// 表格数据
const loading = ref<boolean>(false)
const couponList = ref<any[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列定义
const columns = [
  {
    title: '优惠券名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '优惠券类型',
    dataIndex: 'type',
    key: 'type',
    width: 100
  },
  {
    title: '优惠金额',
    dataIndex: 'discountAmount',
    key: 'discountAmount',
    width: 70
  },
  {
    title: '最低消费',
    dataIndex: 'minAmount',
    key: 'minAmount',
    width: 70
  },
  {
    title: '有效期',
    key: 'validPeriod',
    width: 150
  },
  {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock',
    width: 60
  },
  {
    title: '是否秒杀',
    key: 'isSeckill',
    width: 70
  },
  {
    title: '秒杀时间',
    key: 'seckillPeriod',
    width: 200
  },
  {
    title: '操作',
    key: 'action',
    width: 120
  }
]

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '--'
  return dayjs(date).format('YYYY-MM-DD')
}

// 格式化日期时间
const formatDateTime = (date: string) => {
  if (!date) return '--'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取优惠券列表
const fetchCouponList = async () => {
  loading.value = true
  try {
    const response = await listCouponVoByPageUsingPost({
      ...searchForm.value
    })
    if (response.data) {
      couponList.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.current = response.data.current || 1
      pagination.pageSize = response.data.size || 10  
    } else {
      message.error('获取优惠券列表失败')
    }
  } catch (error: any) {
    message.error('获取优惠券列表出错')
    console.error('获取优惠券列表出错:', error)
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  searchForm.value.current = pag.current
  searchForm.value.pageSize = pag.pageSize
  fetchCouponList()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  searchForm.value.current = 1
  fetchCouponList()
}

// 重置处理
const handleReset = () => {
  searchForm.value.name = undefined
  searchForm.value.type = undefined
  searchForm.value.isSeckill = undefined
  pagination.current = 1
  searchForm.value.current = 1
  fetchCouponList()
}

// 编辑弹窗相关
const modalVisible = ref<boolean>(false)
const modalTitle = ref<string>('新增优惠券')
const formRef = ref()
const formState = reactive({
  name: '',
  type: COUPON_TYPE.FIXED,
  discountAmount: 0,
  minAmount: 0,
  stock: 100,
  startTime: '',
  endTime: '',
  isSeckill: false,
  seckillStartTime: '',
  seckillEndTime: '',
  id: undefined
})

// 日期范围
const timeRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
  dayjs().startOf('day'),
  dayjs().add(30, 'days').endOf('day')
])

// 秒杀时间和持续时间
const seckillStartTime = ref<dayjs.Dayjs | null>(null)
const seckillDurationHours = ref<number>(24) // 默认24小时
const seckillDurationMinutes = ref<number>(0) // 默认0分钟

// 计算秒杀结束时间
const calculateSeckillEndTime = () => {
  if (seckillStartTime.value) {
    const hours = seckillDurationHours.value || 0
    const minutes = seckillDurationMinutes.value || 0
    
    if (hours === 0 && minutes === 0) {
      // 至少设置1分钟的持续时间
      seckillDurationMinutes.value = 1
      const endTime = dayjs(seckillStartTime.value).add(1, 'minute')
      formState.seckillEndTime = endTime.toISOString()
    } else {
      const endTime = dayjs(seckillStartTime.value)
        .add(hours, 'hour')
        .add(minutes, 'minute')
      formState.seckillEndTime = endTime.toISOString()
    }
  }
}

// 监听秒杀开始时间变化
watch(seckillStartTime, (newVal) => {
  if (newVal) {
    formState.seckillStartTime = newVal.toISOString()
    calculateSeckillEndTime()
  } else {
    formState.seckillStartTime = ''
    formState.seckillEndTime = ''
  }
})

// 监听日期范围变化，更新表单值
watch(timeRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    formState.startTime = newVal[0].toISOString()
    formState.endTime = newVal[1].toISOString()
  }
})

// 验证规则
const rules: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
  discountAmount: [{ required: true, message: '请输入优惠金额/折扣', trigger: 'blur' }],
  minAmount: [{ required: true, message: '请输入最低消费金额', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
  validTimeRange: [{ required: true, message: '请选择有效时间范围', trigger: 'change', validator: (rule, value) => {
    if (timeRange.value && timeRange.value.length === 2) {
      return Promise.resolve();
    }
    return Promise.reject('请选择有效时间范围');
  }}],
  seckillStartTime: [{ 
    required: true, 
    message: '请选择秒杀开始时间', 
    trigger: 'change',
    validator: (rule, value) => {
      if (!formState.isSeckill) {
        return Promise.resolve();
      }
      if (seckillStartTime.value) {
        return Promise.resolve();
      }
      return Promise.reject('请选择秒杀开始时间');
    }
  }],
  seckillDuration: [{ 
    required: true, 
    message: '请输入秒杀持续时间', 
    trigger: 'blur',
    validator: (rule, value) => {
      if (!formState.isSeckill) {
        return Promise.resolve();
      }
      const hours = seckillDurationHours.value || 0
      const minutes = seckillDurationMinutes.value || 0
      if (hours > 0 || minutes > 0) {
        return Promise.resolve();
      }
      return Promise.reject('请输入秒杀持续时间');
    }
  }],
}

// 新增优惠券
const handleAdd = () => {
  resetForm()
  modalTitle.value = '新增优惠券'
  modalVisible.value = true
}

// 编辑优惠券
const handleEdit = (record: any) => {
  resetForm()
  modalTitle.value = '编辑优惠券'
  
  // 填充表单数据
  formState.id = record.id
  formState.name = record.name || ''
  formState.type = record.type || COUPON_TYPE.FIXED
  formState.discountAmount = record.discountAmount || 0
  formState.minAmount = record.minAmount || 0
  formState.stock = record.stock || 0
  
  // 设置时间范围
  if (record.startTime && record.endTime) {
    timeRange.value = [
      dayjs(record.startTime),
      dayjs(record.endTime)
    ]
    formState.startTime = record.startTime
    formState.endTime = record.endTime
  }
  
  // 设置秒杀相关字段
  formState.isSeckill = !!record.seckillStartTime
  if (record.seckillStartTime) {
    seckillStartTime.value = dayjs(record.seckillStartTime)
    formState.seckillStartTime = record.seckillStartTime
    formState.seckillEndTime = record.seckillEndTime
    
    // 计算持续时间（小时和分钟）
    if (record.seckillStartTime && record.seckillEndTime) {
      const start = dayjs(record.seckillStartTime)
      const end = dayjs(record.seckillEndTime)
      const durationMinutes = end.diff(start, 'minute')
      seckillDurationHours.value = Math.floor(durationMinutes / 60)
      seckillDurationMinutes.value = durationMinutes % 60
    }
  }
  
  modalVisible.value = true
}

// 删除优惠券
const handleDelete = async (record: any) => {
  try {
    const response = await deleteCouponUsingPost({ id: record.id })
    if (response.data) {
      message.success('删除优惠券成功')
      fetchCouponList()
    } else {
      message.error('删除优惠券失败')
    }
  } catch (error: any) {
    message.error('删除优惠券出错')
    console.error('删除优惠券出错:', error)
  }
}

// 重置表单
const resetForm = () => {
  formState.id = undefined
  formState.name = ''
  formState.type = COUPON_TYPE.FIXED
  formState.discountAmount = 0
  formState.minAmount = 0
  formState.stock = 100
  formState.isSeckill = false
  formState.seckillStartTime = ''
  formState.seckillEndTime = ''
  
  timeRange.value = [
    dayjs().startOf('day'),
    dayjs().add(30, 'days').endOf('day')
  ]
  formState.startTime = timeRange.value[0].toISOString()
  formState.endTime = timeRange.value[1].toISOString()
  
  seckillStartTime.value = null
  seckillDurationHours.value = 24
  seckillDurationMinutes.value = 0
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const handleModalOk = () => {
  formRef.value.validate().then(async () => {
    try {
      // 如果不是秒杀券，清空秒杀相关字段
      if (!formState.isSeckill) {
        formState.seckillStartTime = ''
        formState.seckillEndTime = ''
      }
      
      if (formState.id) {
        // 更新优惠券
        const response = await updateCouponUsingPost({
          ...formState
        })
        if (response.data) {
          message.success('更新优惠券成功')
          modalVisible.value = false
          fetchCouponList()
        } else {
          message.error('更新优惠券失败')
        }
      } else {
        // 新增优惠券
        const response = await addCouponUsingPost({
          name: formState.name,
          type: formState.type,
          discountAmount: formState.discountAmount,
          minAmount: formState.minAmount,
          stock: formState.stock,
          startTime: formState.startTime,
          endTime: formState.endTime,
          seckillStartTime: formState.seckillStartTime,
          seckillEndTime: formState.seckillEndTime,
        })
        if (response.data) {
          message.success('新增优惠券成功')
          modalVisible.value = false
          fetchCouponList()
        } else {
          message.error('新增优惠券失败')
        }
      }
    } catch (error: any) {
      message.error('提交表单出错')
      console.error('提交表单出错:', error)
    }
  }).catch((error: any) => {
    console.error('表单验证失败:', error)
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCouponList()
})
</script>

<style scoped>
.coupon-container {
  padding: 10px 0;
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.search-buttons {
  margin-right: auto;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f7f7f7;
}

:deep(.ant-tag) {
  margin-right: 0;
}
</style> 